2
0

get-url.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi';
  2. import { FileService } from '@/server/modules/files/file.service';
  3. import { ErrorSchema } from '@/server/utils/errorHandler';
  4. import { AppDataSource } from '@/server/data-source';
  5. import { AuthContext } from '@/server/types/context';
  6. import { authMiddleware } from '@/server/middleware/auth.middleware';
  7. // 获取文件URL路由
  8. const getFileUrlRoute = createRoute({
  9. method: 'get',
  10. path: '/{id}/url',
  11. middleware: [authMiddleware],
  12. request: {
  13. params: z.object({
  14. id: z.coerce.number().openapi({
  15. param: { name: 'id', in: 'path' },
  16. example: 1,
  17. description: '文件ID'
  18. })
  19. })
  20. },
  21. responses: {
  22. 200: {
  23. description: '获取文件URL成功',
  24. content: {
  25. 'application/json': {
  26. schema: z.object({
  27. url: z.string().url().openapi({
  28. description: '文件访问URL',
  29. example: 'https://minio.example.com/bucket/file-key'
  30. })
  31. })
  32. }
  33. }
  34. },
  35. 404: {
  36. description: '文件不存在',
  37. content: { 'application/json': { schema: ErrorSchema } }
  38. },
  39. 500: {
  40. description: '服务器错误',
  41. content: { 'application/json': { schema: ErrorSchema } }
  42. }
  43. }
  44. });
  45. // 创建路由实例
  46. const app = new OpenAPIHono<AuthContext>().openapi(getFileUrlRoute, async (c) => {
  47. try {
  48. const { id } = c.req.valid('param');
  49. // 创建文件服务实例
  50. const fileService = new FileService(AppDataSource);
  51. const url = await fileService.getFileUrl(id);
  52. return c.json({ url }, 200);
  53. } catch (error) {
  54. const message = error instanceof Error ? error.message : '获取文件URL失败';
  55. const code = (error instanceof Error && error.message === '文件不存在') ? 404 : 500;
  56. return c.json({ code, message }, code);
  57. }
  58. });
  59. export default app;